<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import {useAuthStore} from '@/stores/modules/authStore.js'
import {ElMessage, ElDialog, ElUpload} from 'element-plus'
import {userAPI} from '@/api/user'
import router from "@/router/index.js";

const authStore = useAuthStore()
const isLoading = ref(false)
const isEditing = ref(false)

const showPasswordDialog = ref(false)
const showphoneDialog = ref(false)
const showAuthDialog = ref(false)
const countdown = ref(0)
const authStatus = ref(0) // '0'=未认证, '1'=审核中, '2'=已认证
let countdownTimer = null


// 表单数据
const profileForm = ref({
  username: '',
  email: '',
})

// 实名认证表单数据
const authForm = ref({
  realName: '',
  idCard: '',
  idCardFront: '',
  idCardBack: ''
})

// 实名认证表单验证规则
const authRules = {
  realName: [
    {required: true, message: '请输入真实姓名', trigger: 'blur'},
    {min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur'}
  ],
  idCard: [
    {required: true, message: '请输入身份证号', trigger: 'blur'},
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
      message: '请输入正确的身份证号格式',
      trigger: 'blur'
    }
  ],
  idCardFront: [
    {required: true, message: '请输入身份证正面URL', trigger: 'blur'},
    {
      pattern: /^https?:\/\/.+/,
      message: '请输入有效的URL地址',
      trigger: 'blur'
    }
  ],
  idCardBack: [
    {required: true, message: '请输入身份证反面URL', trigger: 'blur'},
    {
      pattern: /^https?:\/\/.+/,
      message: '请输入有效的URL地址',
      trigger: 'blur'
    }
  ]
}

// 密码表单数据
const passwordForm = ref({
  password: '',
  newPassword: '',
  confirmPassword: ''
})

// 手机号表单数据
const phoneForm = ref({
  oldMobile: '',
  newMobile: '',
  code: ''
})

// 密码表单验证规则
const passwordRules = ref({
  password: [
    {required: true, message: '请输入当前密码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 手机号表单验证规则
const phoneRules = {
  oldMobile: [
    {required: true, message: '请输入当前手机号', trigger: 'blur'}
  ],
  newMobile: [
    {required: true, message: '请输入新手机号', trigger: 'blur'},
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === phoneForm.value.oldMobile) {
          callback(new Error('新手机号不能与旧手机号相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {pattern: /^\d{3,6}$/, message: '验证码为3-6位数字', trigger: 'blur'}
  ]
}

// 获取认证状态
const fetchAuthStatus = async () => {
  try {
    const response = await userAPI.getAuthStatus({ userId: authStore.userInfo.id })
    // 使用 Object.assign 确保触发响应式更新
    authStatus.value = Number(response.authStatus) || 0
    console.log("强制设置后的authStatus:", authStatus.value)
  } catch (err) {
    authStatus.value = 0 // 确保回退为数字
  }
}


// 加载用户信息
const loadUserProfile = async () => {
  try {
    isLoading.value = true
    await authStore.fetchUserProfile()
    await fetchAuthStatus() // 新增：加载用户信息后获取认证状态
    console.log("authStatus2",authStatus.value)
    profileForm.value = {
      username: authStore.userInfo.username || '',
      email: authStore.userInfo.email || ''
    }
  } catch (err) {
    ElMessage.error('加载个人信息失败,请尝试重新登录: ' + err.message)
  } finally {
    isLoading.value = false
  }
}

// 提交表单，更新用户信息
const submitForm = async () => {
  try {
    // 只提交用户名和邮箱
    const updateData = {
      username: profileForm.value.username,
      email: profileForm.value.email
    }
    await userAPI.updateUserProfile(updateData)
    // 更新本地存储的用户信息
    authStore.userInfo.username = updateData.username
    authStore.userInfo.email = updateData.email
    localStorage.setItem('userInfo', JSON.stringify(authStore.userInfo))

    ElMessage.success('个人信息更新成功')
    isEditing.value = false
  } catch (err) {
    ElMessage.error('更新失败: ' + err.message)
  }
}

// 取消编辑
const cancelEdit = () => {
  profileForm.value = {
    username: authStore.userInfo.username || '',
    email: authStore.userInfo.email || ''
  }
  isEditing.value = false
}

// 打开修改密码对话框
const openPasswordDialog = () => {
  passwordForm.value = {
    password: '',
    newPassword: '',
    confirmPassword: ''
  }
  showPasswordDialog.value = true
}

// 打开修改手机号对话框
const openphoneDialog = () => {
  phoneForm.value = {
    oldMobile: authStore.userInfo.phone,
    newMobile: '',
    code: ''
  }
  showphoneDialog.value = true
}

// 打开实名认证对话框
const openAuthDialog = () => {
  authForm.value = {
    realName: '',
    idCard: '',
    idCardFront: '',
    idCardBack: ''
  }
  showAuthDialog.value = true
}

// 发送验证码
const sendVerifyCode = async () => {
  if (!phoneForm.value.newMobile) {
    ElMessage.warning('请先输入新手机号')
    return
  }

  if (!/^1[3-9]\d{9}$/.test(phoneForm.value.newMobile)) {
    ElMessage.warning('请输入正确的新手机号')
    return
  }

  try {
    ElMessage.success('验证码已发送')
    startCountdown()
  } catch (err) {
    ElMessage.error('发送验证码失败: ' + err.message)
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
    }
  }, 1000)
}

// 提交修改手机号
const submitphoneChange = async () => {
  try {
    const data = {
      userId: authStore.userInfo.id,
      ...phoneForm.value
    }
    await userAPI.resetPhone(data)
    ElMessage.success('手机号修改成功')

    // 更新本地存储的用户信息
    authStore.userInfo.phone = phoneForm.value.newMobile
    localStorage.setItem('userInfo', JSON.stringify(authStore.userInfo))

    showphoneDialog.value = false
    await loadUserProfile()
  } catch (err) {
    ElMessage.error('手机号修改失败: ' + err.message)
  } finally {
    isLoading.value = false
  }
}

// 提交修改密码
const submitPassword = async () => {
  try {
    const data = {
      userId: authStore.userInfo.id,
      ...passwordForm.value
    }
    await userAPI.changePassword(data)
    ElMessage.success('密码修改成功，请重新登录')
    setTimeout(() => {
      router.push({name: 'Login'})
      window.location.reload()
      authStore.logout()
    }, 1700)
  } catch (err) {
    ElMessage.error('密码修改失败: ' + err.message)
  }
}


// 提交实名认证
const submitAuth = async () => {
  try {
    const data = {
      realName: authForm.value.realName,
      idCard: authForm.value.idCard,
      idCardFront: authForm.value.idCardFront,
      idCardBack: authForm.value.idCardBack,
      userId: authStore.userInfo.id
    }
    await userAPI.submitAuth(data)
    ElMessage.success('实名认证提交成功')
    showAuthDialog.value = false
    await fetchAuthStatus() // 更新认证状态
  } catch (err) {
    ElMessage.error('实名认证提交失败: ' + err.message)
  }
}

// 处理身份证上传
const handleIdCardUpload = async (file, type) => {
  try {
    const formData = new FormData()
    formData.append('file', file)

    // 调用上传API
    const response = await userAPI.uploadFile(formData)

    if (type === 'front') {
      authForm.value.idCardFront = response.data.url // 存储返回的URL
    } else {
      authForm.value.idCardBack = response.data.url // 存储返回的URL
    }

    ElMessage.success('上传成功')
  } catch (err) {
    ElMessage.error('上传失败: ' + err.message)
  }
}

onMounted(() => {
  loadUserProfile()
})

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人中心</h2>
    </div>
    <div class="profile-header">
      <div class="button-group">
        <el-button
            type="primary"
            @click="openphoneDialog"
        >
          换绑手机号
        </el-button>
        <el-button
            type="primary"
            @click="openPasswordDialog"
        >
          修改密码
        </el-button>
        <el-button
            v-if="!isEditing"
            type="primary"
            @click="isEditing = true"
        >
          编辑信息
        </el-button>
        <el-button
            type="primary"
            @click="openAuthDialog"
            v-if="!authStatus || authStatus === 0||authStatus===3"
        >
          实名认证
        </el-button>
      </div>
    </div>

    <div class="profile-content">
      <div class="basic-info">
        <h3>基本信息</h3>
        <el-skeleton :loading="isLoading" animated>
          <template #template>
            <el-skeleton-item variant="text" style="width: 30%"/>
            <el-skeleton-item variant="text" style="width: 50%"/>
            <el-skeleton-item variant="text" style="width: 40%"/>
          </template>
          <template #default>
            <el-form
                v-if="isEditing"
                :model="profileForm"
                label-width="100px"
            >
              <el-form-item label="用户名">
                <el-input
                    v-model="profileForm.username"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="profileForm.email"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm">
                  保存
                </el-button>
                <el-button @click="cancelEdit">
                  取消
                </el-button>
              </el-form-item>
            </el-form>
            <div v-else class="info-display">
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">用户名:</span>
                  <span class="value">{{ authStore.userInfo?.username || '未设置' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">真实姓名:</span>
                  <span class="value">{{ authStore.userInfo?.name || '未设置' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">手机号:</span>
                  <span class="value">{{ authStore.userInfo?.phone || '未设置' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">邮箱:</span>
                  <span class="value">{{ authStore.userInfo?.email || '未设置' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">用户类型:</span>
                  <span class="value">
                    {{
                      authStore.userInfo?.userType === 'ADMIN' ? '管理员' :
                          authStore.userInfo?.userType === 'LAWYER' ? '律师' : '普通用户'
                    }}
                  </span>
                </div>
                <div class="info-item">
                  <span class="label">账号状态:</span>
                  <span class="value">{{ authStore.userInfo?.authStatus == '1' ? '启用' : '禁用' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">实名认证状态:</span>
                  <span class="value">
                  {{
                      authStatus === 2 ? '已认证' :
                          authStatus === 1 ? '审核中' :
                              authStatus === 3 ?'认证未通过':'未认证'
                    }}
                  </span>
                </div>
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>
    </div>

    <!-- 修改手机号对话框 -->
    <el-dialog
        v-model="showphoneDialog"
        title="换绑手机号"
        width="30%"
    >
      <el-form
          :model="phoneForm"
          :rules="phoneRules"
          label-width="120px"
      >
        <el-form-item label="当前手机号" prop="oldMobile">
          <el-input
              v-model="phoneForm.oldMobile"
              disabled
          />
        </el-form-item>
        <el-form-item label="新手机号" prop="newMobile">
          <el-input
              v-model="phoneForm.newMobile"
              placeholder="请输入新手机号"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input
                v-model="phoneForm.code"
                placeholder="请输入验证码"
                maxlength="6"
            />
            <el-button
                type="primary"
                @click="sendVerifyCode"
                :disabled="countdown > 0"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showphoneDialog = false">取消</el-button>
        <el-button
            type="primary"
            @click="submitphoneChange"
            :loading="isLoading"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
        v-model="showPasswordDialog"
        title="修改密码"
        width="30%"
    >
      <el-form
          :model="passwordForm"
          :rules="passwordRules"
          label-width="120px"
      >
        <el-form-item label="当前密码" prop="password">
          <el-input
              v-model="passwordForm.password"
              type="password"
              show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPassword">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 实名认证对话框 -->
    <el-dialog
        v-model="showAuthDialog"
        title="实名认证"
        width="40%"
    >
      <el-form
          :model="authForm"
          :rules="authRules"
          label-width="120px"
      >
        <el-form-item label="真实姓名" prop="realName">
          <el-input
              v-model="authForm.realName"
              placeholder="请输入真实姓名"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input
              v-model="authForm.idCard"
              placeholder="请输入身份证号"
              maxlength="18"
          />
        </el-form-item>
        <el-form-item label="身份证正面URL" prop="idCardFront">
          <el-input
              v-model="authForm.idCardFront"
              placeholder="请输入身份证正面URL"
          />
        </el-form-item>
        <el-form-item label="身份证反面URL" prop="idCardBack">
          <el-input
              v-model="authForm.idCardBack"
              placeholder="请输入身份证反面URL"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAuthDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAuth">提交认证</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 样式保持不变 */
.profile-container {
  max-width: 900px;
  margin: 20px auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e6e6e6;
}

.profile-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8f4ff;
  width: 100%;
}

.profile-header h2 {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  text-align: center;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 15px;
  width: 100%;
}

.profile-content {
  padding: 0 15px;
}

.basic-info {
  margin-bottom: 40px;
  background: #f9f9f9;
  padding: 25px;
  border-radius: 8px;
  border: 1px solid #e8f4ff;
}

.basic-info h3 {
  color: #3498db;
  font-size: 20px;
  margin: 0 0 25px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8f4ff;
}

.info-display {
  padding: 10px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.info-item {
  display: flex;
  margin-bottom: 18px;
  font-size: 16px;
  line-height: 1.6;
}

.info-item .label {
  width: 100px;
  color: #7f8c8d;
  font-weight: 500;
}

.info-item .value {
  flex: 1;
  color: #2c3e50;
  font-weight: 400;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input .el-input {
  flex: 1;
}

.el-button {
  transition: all 0.3s ease;
}

.el-button--primary {
  background-color: #3498db;
  border-color: #3498db;
}

.el-button--primary:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input {
  border-radius: 4px;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  border-bottom: 1px solid #e8f4ff;
  padding: 15px 20px;
}

.el-dialog__title {
  color: #2c3e50;
  font-weight: 600;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  border-top: 1px solid #e8f4ff;
  padding: 15px 20px;
}

.upload-demo {
  width: 100%;
}

@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .button-group {
    flex-direction: column;
    align-items: center;
  }

  .button-group .el-button {
    width: 100%;
    max-width: 200px;
    margin: 5px 0;
  }

  .profile-container {
    padding: 20px;
  }

  .basic-info {
    padding: 15px;
  }
}
</style>